<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料分类" prop="materialCategory">
        <el-select v-model="queryParams.materialCategory" placeholder="请选择物料分类" clearable>
          <el-option
            v-for="dict in dict.type.sys_material_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料类型" prop="materialType">
        <el-select v-model="queryParams.materialType" placeholder="请选择物料类型" clearable>
          <el-option
            v-for="dict in dict.type.sys_material_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="物料状态" clearable>
          <el-option key="0" label="正常" value="0" />
          <el-option key="1" label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['test:material:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['test:material:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['test:material:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['test:material:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['test:material:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="物料编码" align="left" prop="materialCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="物料名称" align="left" prop="materialName" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="物料分类" align="center" prop="materialCategory" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_material_category" :value="scope.row.materialCategory"/>
        </template>
      </el-table-column>
      <el-table-column label="计量单位" align="center" prop="unitOfMeasure" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_unit_of_measure" :value="scope.row.unitOfMeasure"/>
        </template>
      </el-table-column>
      <el-table-column label="规格型号" align="left" prop="specifications" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="销售价格" align="center" prop="salePrice" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.salePrice">￥{{ scope.row.salePrice }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="物料类型" align="center" prop="materialType" width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_material_type" :value="scope.row.materialType"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['test:material:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['test:material:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料信息对话框 -->
    <el-drawer
      :title="title"
      :visible.sync="open"
      direction="rtl"
      size="67%"
      :before-close="cancel"
    >
      <div style="padding: 0 20px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="物料名称" prop="materialName">
                <el-input v-model="form.materialName" placeholder="请输入物料名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料编码" prop="materialCode">
                <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="物料分类" prop="materialCategory">
                <el-select v-model="form.materialCategory" placeholder="请选择物料分类">
                  <el-option
                    v-for="dict in dict.type.sys_material_category"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计量单位" prop="unitOfMeasure">
                <el-select v-model="form.unitOfMeasure" placeholder="请选择计量单位">
                  <el-option
                    v-for="dict in dict.type.sys_unit_of_measure"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="规格型号" prop="specifications">
                <el-input v-model="form.specifications" placeholder="请输入规格型号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售价格" prop="salePrice">
                <el-input-number v-model="form.salePrice" :precision="2" :min="0" :max="99999999.99" placeholder="请输入销售价格" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="物料类型" prop="materialType">
                <el-select v-model="form.materialType" placeholder="请选择物料类型">
                  <el-option
                    v-for="dict in dict.type.sys_material_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物料状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio key="0" label="0">正常</el-radio>
                  <el-radio key="1" label="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="padding: 20px 0 0 100px;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 物料详情对话框 -->
    <el-drawer
      title="物料详情"
      :visible.sync="detailOpen"
      direction="rtl"
      size="67%"
    >
      <div style="padding: 0 20px 20px 20px;">
        <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item label="物料名称">{{ detailForm.materialName }}</el-descriptions-item>
          <el-descriptions-item label="物料编码">{{ detailForm.materialCode }}</el-descriptions-item>
          <el-descriptions-item label="物料分类">
            <dict-tag :options="dict.type.sys_material_category" :value="detailForm.materialCategory"/>
          </el-descriptions-item>
          <el-descriptions-item label="计量单位">
            <dict-tag :options="dict.type.sys_unit_of_measure" :value="detailForm.unitOfMeasure"/>
          </el-descriptions-item>
          <el-descriptions-item label="规格型号">{{ detailForm.specifications || '-' }}</el-descriptions-item>
          <el-descriptions-item label="销售价格">
            <span v-if="detailForm.salePrice">￥{{ detailForm.salePrice }}</span>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item label="物料类型">
            <dict-tag :options="dict.type.sys_material_type" :value="detailForm.materialType"/>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="detailForm.status === '0' ? 'success' : 'danger'">
              {{ detailForm.status === '0' ? '正常' : '停用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建者">{{ detailForm.createBy }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新者">{{ detailForm.updateBy || '-' }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ detailForm.updateTime || '-' }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailForm.remark || '-' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的物料数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial } from "@/api/test/material";
import { getToken } from "@/utils/auth";

export default {
  name: "Material",
  dicts: ['sys_material_category', 'sys_material_type', 'sys_unit_of_measure'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料信息表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: null,
        materialCode: null,
        materialCategory: null,
        materialType: null,
        status: null
      },
      // 表单参数
      form: {},
      // 详情表单参数
      detailForm: {},
      // 表单校验
      rules: {
        materialName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" },
          { max: 100, message: "物料名称不能超过100个字符", trigger: "blur" }
        ],
        materialCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" },
          { max: 50, message: "物料编码不能超过50个字符", trigger: "blur" }
        ],
        materialCategory: [
          { max: 50, message: "物料分类不能超过50个字符", trigger: "blur" }
        ],
        unitOfMeasure: [
          { max: 20, message: "计量单位不能超过20个字符", trigger: "blur" }
        ],
        specifications: [
          { max: 200, message: "规格型号不能超过200个字符", trigger: "blur" }
        ]
      },
      // 上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/test/material/importData"
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物料信息列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        materialName: null,
        materialCode: null,
        materialCategory: null,
        unitOfMeasure: null,
        specifications: null,
        salePrice: null,
        materialType: "1",
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialId = row.materialId || this.ids
      getMaterial(materialId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料信息";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const materialId = row.materialId;
      getMaterial(materialId).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },
    /** 物料状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.materialName + '"物料吗？').then(function() {
        return updateMaterial(row);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.materialId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialIds = row.materialId || this.ids;
      this.$modal.confirm('是否确认删除物料信息编号为"' + materialIds + '"的数据项？').then(function() {
        return delMaterial(materialIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('test/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('/test/material/importTemplate', {}, `material_template_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style scoped>
.el-upload__tip {
  line-height: 20px;
  margin-top: 7px;
  color: #666;
}
</style> 